//
//  HKLoginViewController.m
//  AQBPolice
//
//  Created by apple on 2017/7/4.
//  Copyright © 2017年 eight. All rights reserved.
//

#import "HKLoginViewController.h"
#import "ABCIntroView.h"

@interface HKLoginViewController ()<UITextFieldDelegate, ABCIntroViewDelegate>
/**
 获取验证码按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *getMsgButton;
/**
 输入手机号textField
 */
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;

@property (nonatomic, strong) ABCIntroView *introView;

@end

@implementation HKLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //展示引导界面
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![defaults objectForKey:@"everLaunched"]) {
        [defaults setBool:YES forKey:@"everLaunched"];
        HKLog(@"第一次加载");
        self.introView = [[ABCIntroView alloc] initWithFrame:self.view.frame];
        self.introView.delegate = self;
        self.introView.backgroundColor = [UIColor colorWithWhite:0.149 alpha:1.000];
        [self.view addSubview:self.introView];
    }
    
    
    //修改状态栏的颜色为白色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    // 监听文本输入框的改变
    // 1.拿到通知中心
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    // 2.注册监听
    [center addObserver:self selector:@selector(textChanged) name:UITextFieldTextDidChangeNotification object:self.phoneTextField];
    //按钮不能点击，颜色是灰色的
    self.getMsgButton.enabled = NO;
    [self.getMsgButton setBackgroundColor:HKColor(216, 216, 216)];
}

- (void)textChanged {
    //文本框有输入，按钮变成橙色
    if (self.phoneTextField.text.length > 0) {
        self.getMsgButton.enabled = YES;
        [self.getMsgButton setBackgroundColor:HKColor(253, 151, 39)];
    }
}

//获取验证码按钮点击
- (IBAction)getMsgButtonClicked:(id)sender {
    HKLog(@"验证手机号");
    BOOL isPhoneNumber = [self valiMobile:self.phoneTextField.text];
    if (isPhoneNumber) {
        //1.保存手机号
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:self.phoneTextField.text forKey:@"getPhoneNumber"];
        //2.发送验证码
        //2.1访问网络验证手机号是否可用
        NSURLSession *session1 = [NSURLSession sharedSession];
        NSString *urlString1 = [NSString stringWithFormat:@"http://202.111.178.10:28084/mobile/police/isTelAvailable?telephone=%@", self.phoneTextField.text];
        NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString1]];
        request1.HTTPMethod = @"GET";
        NSURLSessionDataTask *task1 = [session1 dataTaskWithRequest:request1 completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (data == nil) {
                [MBProgressHUD showError:@"网络错误" toView:self.view];
            }else {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                if ([dict[@"meta"] isEqual: @"success"]) {
                    //2.2手机号可用，发送验证码
                    //2.跳转到验证码输入界面
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self performSegueWithIdentifier:@"login2message" sender:nil];
                    });
                    //向后台发送短信重新获取验证码
                    NSURLSession *session = [NSURLSession sharedSession];
                    NSString *urlString = [baseURL stringByAppendingString:@"mobile/common/sendMessage/"];
                    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
                    request.HTTPMethod = @"POST";
                    request.HTTPBody = [[NSString stringWithFormat:@"telephone=%@", kPhoneNumber] dataUsingEncoding:NSUTF8StringEncoding];
                    
                    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                        HKLog(@"----%@", dict);
                    }];
                    [task resume];
                    
                }else {
                    //回到主线程提示手机号不可用
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [MBProgressHUD showError:@"手机号不可用" toView:self.view];
                    });
                }
            }
        }];
        [task1 resume];
    }else {
        //弹窗提示手机号不正确
        [MBProgressHUD showError:@"手机号不正确" toView:self.view];
    }
}

//点击空白处收起键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

/**
 判断手机号
 @param mobile 手机号码
 @return 返回真假
 */
- (BOOL)valiMobile:(NSString *)mobile {
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(17[5,6])|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

#pragma mark - ABCIntroViewDelegate Methods

-(void)onDoneButtonPressed{
    
    //    Uncomment so that the IntroView does not show after the user clicks "DONE"
    //    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //    [defaults setObject:@"YES"forKey:@"intro_screen_viewed"];
    //    [defaults synchronize];
    
    [UIView animateWithDuration:1.0 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.introView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.introView removeFromSuperview];
    }];
}


@end
